// src/api/fetcher.ts
import { message } from 'antd';

const env = process.env.API_ENV;
const baseURL = env !== 'prd' ? process.env.NEXT_PUBLIC_UAT_API : process.env.NEXT_PUBLIC_API;

// 错误处理函数
const showErrorMessage = (msg: string, url?: string) => {
  if (typeof window !== 'undefined') {
    if(msg === '无此套餐') return;
    message.error(msg || '服务端出错了');
  } else {
    console.error(msg || '服务端出错了');
    console.error('----api url--------:' + url);
  }
};

// 基础fetch方法
async function customFetch<T>(
  url: string, 
  options: RequestInit = {}
): Promise<T> {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), 300000);
  
  try {
    const fullUrl = url.startsWith('http') ? url : `${baseURL}${url}`;
    
    const response = await fetch(fullUrl, {
      ...options,
      signal: controller.signal,
      headers: {
        'Content-Type': 'application/json',
        ...options.headers,
      }
    });

    const data = await response.json();
    
    // 处理响应状态
    if (response.status === 209) {
      showErrorMessage(`接口服务超出限制，请联系管理员`);
      throw new Error('接口服务超出限制');
    }
    
    if (data?.code === 1) {
      return data.data;
    } else if (/^20*/.test(data?.httpCode)) {
      showErrorMessage(data.message);
      return data;
    } else {
      if (data?.httpCode === 500) {
        const msg = data?.msg || data?.message;
        const message = msg && msg.length < 260 ? msg : '服务端出错了';
        showErrorMessage(message);
      } else if (data?.message || data?.msg) {
        return data;
      }
      throw new Error(`接口报错： ${fullUrl}`);
    }
  } catch (error: any) {
    if (error.name === 'AbortError') {
      showErrorMessage('请求超时,服务异常');
    } else if (error instanceof Error) {
      showErrorMessage(error.message);
    }
    throw error;
  } finally {
    clearTimeout(timeoutId);
  }
}

// API方法
export const apiClient = {
  // GET请求
  get: (url: string, params?: Record<string, any>) => {
    const queryString = params ? `?${new URLSearchParams(params).toString()}` : '';
    return customFetch(`${url}${queryString}`);
  },
  
  // POST请求 (form-urlencoded)
  post:(url: string, data?: Record<string, any>) => {
    const formData = data ? new URLSearchParams(data).toString() : '';
    return customFetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: formData,
    });
  },
  
  // POST JSON请求
  postJson: (url: string, data?: any, queryParams?: Record<string, any>) => {
    const queryString = queryParams ? `?${new URLSearchParams(queryParams).toString()}` : '';
    return customFetch(`${url}${queryString}`, {
      method: 'POST',
      body: JSON.stringify(data || {}),
    });
  }
};

